import React from 'react';
import { useState } from 'react';
import { transformAdsProgram } from './common/adsProgramUtil.ts'


export default function PromiseAllTest() {
    const [adPlTitle, setAdPlTitle] = useState('___');
    const [sellers, setSellers] = useState([]);

    function handleChange(e) {
        const program = e.target.value;
        const adPlTitle = transformAdsProgram(program, true);
        setAdPlTitle(adPlTitle);
    }

    function runAllPromise() {
        const promises = [
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve({ seller_id: 1, seller_name: 'seller1' });
                }, 200); // 延迟200ms执行
            }),
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve({ seller_id: 2, seller_name: 'seller2' });
                }, 100);
            }),
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    reject('error');
                }, 150);
            }),
            new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve({ seller_id: 4, seller_name: 'seller4' });
                }, 500);
            }),
        ];

        Promise.all(promises.map(promise =>
            // catch后返回null，某个promise异常不会影响其他promise的执行
            promise.catch(error => {
                console.log('error: ', error);
                return null;
            })
        )
        ).then(results => {
            // Promise.all(), result填充顺序按promise数组顺序
            console.log('all finshed, ', results);
            // 过滤掉null的结果
            const filterSellers = results.filter(result => result !== null);
            console.log('after filter sellers: ', filterSellers);
            setSellers(filterSellers);
        })
        .catch(errors => { console.log('all error') });
    }


    return (
        <div style={{display: 'flex'}}>
            <div>Promise Test</div>
            <button onClick={runAllPromise}>执行Promise.all</button>
            <ul>
                {sellers.map(seller => (
                    <li key={seller.seller_id}>{seller.seller_name}</li>
                ))}
            </ul>
            <br/>
            <div>
                <select onChange={handleChange}>
                    <option value="" hidden>请选择 Origin AdsTitle</option>
                    <option value="PLS">PLS</option>
                    <option value="PLA">PLA</option>
                    <option value="OA">OA</option>
                </select>
            </div>
            <div>
                After transform AdsTitle:&nbsp; <span style={{color: 'red'}}>{adPlTitle}</span>
            </div>
        </div>
    );
};
